import main from "../dbs/main.db";
import { http } from 'system';

/**
 * 获取抓取内容分页列表
 * @param {number} [sourceId] - 抓取源ID筛选（可选）
 * @param {string} [keyword] - 关键词筛选（可选）
 * @param {number} [analysisStatus] - 分析状态筛选（可选，0:未分析,1:正在分析,2:已分析,3:无效数据）
 * @param {number} [page=1] - 页码（默认1）
 * @param {number} [pageSize=10] - 每页数量（默认10）
 * @returns {Object} 标准响应格式 {code:number, message:string, data: { list:[{id:number, source_id:number, title:string, site_title:string, site_full_url:string, content:string, content_create_at:string, create_at:string, analysis_status:number}], total:number, page:number, pageSize:number }}
 * @example
 * // 使用示例
 * const result = await getContentList(1, "测试", 2, 1, 10);
 * 
 * @clientCall iToolX.modules.contentManager.getContentList()
 * 
 * // 完整的result数据结构说明
 * {
 *   code: 200,
 *   message: '',
 *   data: {
 *     list: [
 *       {
 *         id: 1,
 *         source_id: 1,
 *         title: "示例内容标题",
 *         site_title: "示例站点",
 *         site_full_url: "https://example.com/article/1",
 *         content: "这是抓取到的内容...",
 *         content_create_at: "2023-01-01T00:00:00Z",
 *         create_at: "2023-01-01T00:00:00Z",
 *         analysis_status: 2  // 0:未分析,1:正在分析,2:已分析,3:无效数据
 *       }
 *     ],
 *     total: 100,
 *     page: 1,
 *     pageSize: 10
 *   }
 * }
 */
async function getContentList(sourceId, keyword, analysisStatus, page = 1, pageSize = 10) {
    try {
        const queryParams = {
            "total@": "[]/total",
            "[]": {
                "crawl_site_content": {
                    page,
                    count: pageSize,
                    query: 2,
                    "@column": "id,source_id,title,site_full_url,content,content_create_at,create_at,analysis_status"
                },
                "crawl_sources": {
                    "id@": "crawl_site_content/source_id",
                    "@column": "site_title"
                }
            }
        };

        // 添加筛选条件
        if (sourceId) {
            queryParams["[]"]["crawl_site_content"]["source_id"] = sourceId;
        }

        if (keyword) {
            queryParams["[]"]["crawl_site_content"]["@or"] = {
                "content$": `%${keyword}%`,
                "site_full_url$": `%${keyword}%`,
                "title$": `%${keyword}%`
            };
        }

        if (analysisStatus !== undefined && analysisStatus !== null) {
            queryParams["[]"]["crawl_site_content"]["analysis_status"] = analysisStatus;
        }

        const result = await main.queryAsync(queryParams);

        // 处理返回数据，合并站点标题
        const list = (result["[]"] || []).map(item => {
            return {
                ...item["crawl_site_content"],
                site_title: item["crawl_sources"]?.site_title || ""
            };
        });

        return {
            code: 200,
            message: '',
            data: {
                list,
                total: result.total || 0,
                page,
                pageSize
            }
        };
    } catch (error) {
        console.error('获取内容列表失败:', error);
        return {
            code: 500,
            message: '获取内容列表失败',
            data: error.message
        };
    }
}

/**
 * 获取内容详情
 * @param {number} id - 内容ID
 * @returns {Object} 标准响应格式 {code:number, message:string, data: { id:number, source_id:number, title:string, site_title:string, site_full_url:string, content:string, content_create_at:string, create_at:string, analysis_status:number }}
 * @example
 * // 使用示例
 * const result = await getContentDetail(1);
 * 
 * @clientCall iToolX.modules.contentManager.getContentDetail()
 * 
 * // 完整的result数据结构说明
 * {
 *   code: 200,
 *   message: '',
 *   data: {
 *     id: 1,
 *     source_id: 1,
 *     title: "示例内容标题",
 *     site_title: "示例站点",
 *     site_full_url: "https://example.com/article/1",
 *     content: "这是抓取到的内容...",
 *     content_create_at: "2023-01-01T00:00:00Z",
 *     create_at: "2023-01-01T00:00:00Z",
 *     analysis_status: 2  // 0:未分析,1:正在分析,2:已分析,3:无效数据,
 *     comment:"AI的评论信息"
 *   }
 * }
 */
async function getContentDetail(id) {
    try {
        const result = await main.queryAsync({
            "crawl_site_content": {
                id,
                "@column": "id,source_id,title,site_full_url,content,content_create_at,create_at,analysis_status, comment"
            },
            "crawl_sources": {
                "id@": "crawl_site_content/source_id",
                "@column": "site_title"
            }
        });

        if (!result["crawl_site_content"]?.id) {
            return {
                code: 404,
                message: '内容不存在',
                data: null
            };
        }

        const source = result["crawl_sources"];
        return {
            code: 200,
            message: '',
            data: {
                ...result["crawl_site_content"],
                site_title: source?.site_title || ""
            }
        };
    } catch (error) {
        console.error('获取内容详情失败:', error);
        return {
            code: 500,
            message: '获取内容详情失败',
            data: error.message
        };
    }
}

/**
 * 删除内容
 * @param {number} id - 内容ID
 * @returns {Object} 标准响应格式 {code:number, message:string, data: null}
 * @example
 * // 使用示例
 * const result = await deleteContent(1);
 * 
 * @clientCall iToolX.modules.contentManager.deleteContent()
 * 
 * // 完整的result数据结构说明
 * {
 *   code: 200,
 *   message: '删除成功',
 *   data: null
 * }
 */
async function deleteContent(id) {
    try {
        // 先检查内容是否存在
        const checkResult = await main.queryAsync({
            "crawl_site_content": {
                id,
                "@column": "id"
            }
        });

        if (!checkResult["crawl_site_content"]?.id) {
            return {
                code: 404,
                message: '内容不存在',
                data: null
            };
        }

        // 删除内容
        await main.removeAsync({
            "crawl_site_content": {
                id
            }
        });

        return {
            code: 200,
            message: '删除成功',
            data: null
        };
    } catch (error) {
        console.error('删除内容失败:', error);
        return {
            code: 500,
            message: '删除内容失败',
            data: error.message
        };
    }
}

/**
 * 批量删除内容
 * @param {number[]} ids - 内容ID数组
 * @returns {Object} 标准响应格式 {code:number, message:string, data: null}
 * @example
 * // 使用示例
 * const result = await batchDeleteContent([1, 2, 3]);
 * 
 * @clientCall iToolX.modules.contentManager.batchDeleteContent()
 * 
 * // 完整的result数据结构说明
 * {
 *   code: 200,
 *   message: '批量删除成功',
 *   data: null
 * }
 */
async function batchDeleteContent(ids) {
    try {
        if (!ids || !Array.isArray(ids) || ids.length === 0) {
            return {
                code: 400,
                message: '请提供有效的ID列表',
                data: null
            };
        }

        // 检查所有ID是否存在
        const checkResult = await main.queryAsync({
            "total@": "[]/total",
            "[]": {
                "crawl_site_content": {
                    "id{}": ids,
                    "@column": "id"
                }
            }
        });

        const existingIds = (checkResult["[]"] || []).map(item => item["crawl_site_content"].id);
        const missingIds = ids.filter(id => !existingIds.includes(id));

        if (missingIds.length > 0) {
            return {
                code: 404,
                message: `以下ID不存在: ${missingIds.join(', ')}`,
                data: null
            };
        }
        // 批量删除内容 - 逐个删除
        for (const id of ids) {
            await main.removeAsync({
                "crawl_site_content": {
                    "id": id
                }
            });
        }

        return {
            code: 200,
            message: '批量删除成功',
            data: null
        };
    } catch (error) {
        console.error('批量删除内容失败:', error);
        return {
            code: 500,
            message: '批量删除内容失败',
            data: error.message
        };
    }
}

export { getContentList, getContentDetail, deleteContent, batchDeleteContent };